package com.xmall.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xmall.define.constants.CommonProperties;
import com.xmall.define.dict.LogStatusEnum;
import com.xmall.define.dto.log.RetryLogDto;
import com.xmall.define.request.sys.RetryLogListPageQueryRequest;
import com.xmall.order.define.constants.OrderConstants;
import com.xmall.order.define.constants.OrderProperties;
import com.xmall.order.entity.OrderPaySuccessRetryLog;
import com.xmall.order.mapper.OrderPaySuccessRetryLogMapper;
import com.xmall.order.service.IOrderPaySuccessRetryLogService;
import com.xmall.order.service.IOrderService;
import com.xmall.order.utils.ConvertUtils;
import com.xmall.timer.handler.IRetryLogTaskHandler;
import com.xmall.utils.TimerUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 订单支付成功日志 服务实现类
 */
@Slf4j
@Service
public class OrderPaySuccessRetryLogServiceImpl extends ServiceImpl<OrderPaySuccessRetryLogMapper, OrderPaySuccessRetryLog> implements IOrderPaySuccessRetryLogService, IRetryLogTaskHandler {

    @Resource
    private IOrderService orderService;

    @Resource
    private OrderProperties orderProperties;

    @Resource
    private CommonProperties commonProperties;

    /**
     * 新增数据保存，重复数据不保存
     */
    @Override
    public void saveDuplicate(OrderPaySuccessRetryLog log) {
        this.baseMapper.saveDuplicate(log);
    }

    /**
     * 状态置为完成
     */
    @Override
    public Boolean complete(Long orderId) {
        return this.update(
            new OrderPaySuccessRetryLog(LogStatusEnum.PROCESSED.getStatus()),
            new QueryWrapper<OrderPaySuccessRetryLog>().eq("order_id", orderId).eq("log_status", LogStatusEnum.PROCESSING.getStatus()));
    }

    @Override
    public String key() {
        return OrderConstants.TimerTask.ORDER_PAY_SUCCESS_LOG_RETRY_TASK;
    }

    @Override
    public String name() {
        return "订单支付成功日志任务";
    }

    @Override
    public String cron() {
        return orderProperties.getOrderPaySuccessLogCron();
    }

    @Override
    public void execute() {
        TimerUtils.retryExecute(commonProperties, this, retryLog -> orderService.paySuccess(retryLog));
    }

    /**
     * 是否有异常
     */
    @Override
    public Boolean hasException() {
        return this.count(new QueryWrapper<OrderPaySuccessRetryLog>().gt("retry_count", 0).eq("log_status", LogStatusEnum.PROCESSING.getStatus())) > 0;
    }

    @Override
    public Page<RetryLogDto> retryListPage(RetryLogListPageQueryRequest request) {
        Page<RetryLogDto> result = new Page<>();

        QueryWrapper query = new QueryWrapper();
        query.orderByDesc("retry_count");
        query.orderByDesc("create_time");

        Page<OrderPaySuccessRetryLog> page = this.page(new Page(request.getPage(), request.getPageSize()), query);

        BeanUtils.copyProperties(page, result);

        List<RetryLogDto> retryLogDtoList = page.getRecords().stream().map(retryLog -> {
            RetryLogDto retryLogDto = ConvertUtils.RetryLogModule.INSTANCE.toDtoFromOrderPaySuccess(retryLog);
            retryLogDto.setMeta(retryLog);
            return retryLogDto;
        }).collect(Collectors.toList());

        result.setRecords(retryLogDtoList);
        return result;
    }
}
